#include "StdAfx.h"
#include "SettingManager.h"
#include "Config.h"

class AutoRunLogic
{
public:
	AutoRunLogic()
	{
		mSubKey = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
		mValueName = _T("FastTab");
	}
	void SetAutoRun(bool val)
	{
		if (val)
		{
			Reg();
		}
		else
		{
			UnReg();
		}
	}
	bool GetAutoRun()
	{
		HKEY openKey = 0;
		bool ret = false;
		if (RegOpenKey(HKEY_CURRENT_USER, mSubKey, &openKey) !=  ERROR_SUCCESS)
		{
			ret = false;
			return ret;
		}
		if (openKey)
		{
			DWORD size;
			DWORD type = REG_SZ;
			if (RegQueryValueEx(openKey, mValueName, 0, NULL, NULL, &size) == ERROR_SUCCESS)
			{
				ret = size != 0;
			}
			RegCloseKey(openKey);
		}
		return ret;
	}
private:
	void Reg()
	{
		HKEY openKey = 0;
		if (RegOpenKey(HKEY_CURRENT_USER, mSubKey, &openKey) !=  ERROR_SUCCESS)
		{
			LogError("RegOpenKeyError")
			return ;
		}
		if (openKey)
		{
			TCHAR name[MAX_PATH] = {0};
			::GetModuleFileName(NULL, name, MAX_PATH);
			int len = _tcslen(name);
			LONG ret = RegSetValueEx(openKey, mValueName, 0, REG_SZ, (const BYTE*)name, len *2);

			RegCloseKey(openKey);
		}
		
	}

	void UnReg()
	{
		HKEY openKey = 0;
		if (RegOpenKey(HKEY_CURRENT_USER, mSubKey, &openKey) !=  ERROR_SUCCESS)
		{
			LogError("RegOpenKeyError")
			return ;
		}

		LONG ret = RegDeleteValue(openKey, mValueName);

		RegCloseKey(openKey);
	}
	CString mSubKey;
	CString mValueName;

};

SettingManager::SettingManager(void)
{
	ReloadProperties();
	bool& firstRun = GetModifyProperties().IsFirstRun;
	if (firstRun)
	{
		SetAutoRun(true);
		firstRun = false;
		SaveProperties();
	}
	
}

SettingManager::~SettingManager(void)
{
}

void SettingManager::SetAutoRun( bool val )
{
	AutoRunLogic logic;
	logic.SetAutoRun(val);
}

bool SettingManager::IsAutoRun() const
{
	AutoRunLogic logic;
	return logic.GetAutoRun();
}

void SettingManager::GetCurrDirectory( std::wstring& directory )
{
	TCHAR name[MAX_PATH] = {0};
	::GetModuleFileName(NULL, name, MAX_PATH);

	directory = name;

	directory = directory.substr(0, directory.rfind(_T('\\')) + 1);
}

void SettingManager::ReloadProperties()
{
	std::wstring directory;
	GetCurrDirectory(directory);
	Config config(std::wstring(directory + _T("Config.ini")).c_str());
	LoadFromConfig(&config, &mProperties);
}

void SettingManager::SaveProperties()
{
	std::wstring directory;
	GetCurrDirectory(directory);
	Config config(std::wstring(directory + _T("Config.ini")).c_str());
	SaveToConfig(&config, &mProperties);
	config.Flush();
}